package com.zhaojun.cloud.common.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.FatalBeanException;
import org.springframework.util.Assert;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;

/**
 * wwj
 * 2018/7/17  15:43
 */
public abstract class BeanUtils extends org.springframework.beans.BeanUtils {

    public static void copyProperties(Object source, Object target) throws BeansException {
        copyProperties(source, target,  null, (String[]) null);
    }

    private static void copyProperties(Object source, Object target, Class<?> editable, String... ignoreProperties) {
        Assert.notNull(source, "Source must not be null");
        Assert.notNull(target, "Target must not be null");
        Class<?> actualEditable = target.getClass();
        if (editable != null) {
            if (!editable.isInstance(target)) {
                throw new IllegalArgumentException("Target class [" + target.getClass().getName() + "] not assignable to Editable class [" + editable.getName() + "]");
            }

            actualEditable = editable;
        }

        PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
        List<String> ignoreList = ignoreProperties != null ? Arrays.asList(ignoreProperties) : null;
        PropertyDescriptor[] arr$ = targetPds;
        int len$ = targetPds.length;

        for (int i$ = 0; i$ < len$; ++i$) {
            PropertyDescriptor targetPd = arr$[i$];
            if (targetPd.getWriteMethod() != null && (ignoreProperties == null || !ignoreList.contains(targetPd.getName()))) {
                PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
                if (sourcePd != null && sourcePd.getReadMethod() != null) {
                    try {
                        Method readMethod = sourcePd.getReadMethod();
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                            readMethod.setAccessible(true);
                        }

                        Object value = readMethod.invoke(source);
                        if (value != null) { //不为null 才拷贝
                            Method writeMethod = targetPd.getWriteMethod();
                            if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                                writeMethod.setAccessible(true);
                            }
                            writeMethod.invoke(target, value);
                        }
                    } catch (Throwable var15) {
                        throw new FatalBeanException("Could not copy properties from source to target", var15);
                    }
                }
            }
        }
    }

    /**
     * 忽略大小写Copy属性
     *
     * @param obj    转换的源对象
     * @param result 目标对象
     * @param clz    目标对象class
     * @return 转换后的对象
     */
    public static void transferObjectIgnoreCase(Object obj, Object result, Class clz) {
        try {
            if (obj != null && !obj.equals("")) {
                //获取目标类的属性集合
                Map<String, Field> destPropertyMap = new HashMap<String, Field>();
                for (Field curField : clz.getDeclaredFields()) {
                    destPropertyMap.put(curField.getName().toLowerCase(), curField);
                }
                //拷贝属性
                for (Field curField : obj.getClass().getDeclaredFields()) {
                    Field targetField = destPropertyMap.get(curField.getName().toLowerCase());
                    if (targetField != null) {
                        targetField.setAccessible(true);
                        curField.setAccessible(true);
                        targetField.set(result, curField.get(obj));
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据对象获取Map属性数据
     *  key      |   value
     * fieldName |   fieldValue
     */
    public static Map getMapForObjectField(Object obj) {
        try {
            Map<String, Object> result = new HashMap<>();
            if(!Detect.notNull(obj)){
                return result;
            }
            PropertyDescriptor[] propertyDescriptors = org.springframework.beans.BeanUtils.getPropertyDescriptors(obj.getClass());
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                Method method = propertyDescriptor.getReadMethod();
                //有一些属性的方法不是 public 需要获取权限
                if (!Modifier.isPublic(method.getDeclaringClass().getModifiers())) {
                    method.setAccessible(true);
                }
                Object value = method.invoke(obj);

                if (Date.class.equals(method.getReturnType())) {
                    //时间类型转换成String
                    value = DateUtil.formatDate((Date) value);
                }
                result.put(propertyDescriptor.getName(), Objects.toString(value));
            }
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


}
